<?php

//对象赋值
class BeanUtils
{


    //将一个对象的属性值复制到另一个对象中
    public static function copyProperties($source, $target)
    {
        $sourceReflection = new ReflectionClass($source);
        $targetReflection = new ReflectionClass($target);

        foreach ($sourceReflection->getProperties() as $property) {
            $property->setAccessible(true); // 允许访问私有属性

            $propertyName = $property->getName();
            $propertyValue = $property->getValue($source);

            // 确保目标类有对应属性
            if ($targetReflection->hasProperty($propertyName)) {
                $targetProperty = $targetReflection->getProperty($propertyName);
                $targetProperty->setAccessible(true);
                $targetProperty->setValue($target, $propertyValue);
            }
        }
    }

    //把dto接收的值复制给普通实体类,对象相同属性复制赋值
    static function mapDtoToEntity($dto, $entity)
    {
        $dtoReflection = new ReflectionObject($dto);
        $entityReflection = new ReflectionObject($entity);

        foreach ($dtoReflection->getProperties() as $dtoProperty) {
            $dtoProperty->setAccessible(true);
            $value = $dtoProperty->getValue($dto);

            $entityProperty = $entityReflection->getProperty($dtoProperty->getName());
            $entityProperty->setAccessible(true);
            $entityProperty->setValue($entity, $value);
        }
    }


    //对象转数组
    static function classToArrayWithPrivate($object)
    {
        $reflectionClass = new ReflectionClass($object);
        $properties = $reflectionClass->getProperties();
        $result = [];

        foreach ($properties as $property) {
            $property->setAccessible(true); // 允许访问私有和受保护属性
            $result[$property->getName()] = $property->getValue($object);
        }

        return $result;
    }


    //先转dto赋给entity，后把entity转数组
    static function dtoCopyEntityToArray($dto, $entity)
    {
        self::mapDtoToEntity($dto, $entity);
        $classToArrayWithPrivate = self::classToArrayWithPrivate($entity);
        return $classToArrayWithPrivate;
    }
}

// BeanUtils::mapDtoToEntity($ BloggerDto,$ Blogger);
//$ Blogger = BeanUtils::classToArrayWithPrivate($ BloggerDto);